package com.zzyl.framework.interceptor;

import com.zzyl.common.constant.HttpStatus;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.common.utils.UserThreadLocal;
import com.zzyl.framework.web.service.TokenService;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 微信小程序拦截器
 *
 * @Author mr.chen
 * @Date 2025/5/25 9:27
 */
@Component
public class MemberInterceptor implements HandlerInterceptor {

    @Autowired
    private TokenService tokenService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //非控制层方法
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        //获取token
        String token = request.getHeader(HttpHeaders.AUTHORIZATION);

        //判断token是否为空
        if (StringUtils.isBlank(token)) {
            //为空的话响应401
            response.setStatus(HttpStatus.UNAUTHORIZED);
            return false;
        }

        //解析token
        try {
            Claims claims = tokenService.parseToken(token);
            //获取用户id
            Object id = claims.get("userId");
            Long userId = Long.valueOf(String.valueOf(id));
            UserThreadLocal.set(userId);
        } catch (Exception e) {
            e.printStackTrace();
            //解析错误响应401
            response.setStatus(HttpStatus.UNAUTHORIZED);
            return false;
        }
        //放行
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    UserThreadLocal.remove();
    }
}
